// pages/user/my-exchanges/my-exchanges.ts
import { goToPage, PAGES } from '../../../config/pages';
import { getIntegralOrderList } from '../../../api/points_mall.js';

// 定义兑换记录数据类型
interface ExchangeRecord {
  id: number;
  orderId: string;
  productName: string;
  productImage: string;
  points: number;
  exchangeTime: string;
  status: number;
  statusName: string;
  recipientName: string;
  recipientPhone: string;
  recipientAddress: string;
  trackingNumber: string;
  deliveryName: string;
  deliveryType: string;
  totalNum: number;
  price: number;
  remark: string;
}

Page({
  data: {
    currentFilter: 'all',
    exchanges: [] as ExchangeRecord[],
    filteredExchanges: [] as ExchangeRecord[],
    statusMap: {
      1: { text: '待发货', class: 'status-pending' },
      2: { text: '已发货', class: 'status-shipped' },
      3: { text: '已收货', class: 'status-completed' }
    } as { [key: number]: { text: string; class: string } }
  },

  onLoad() {
    this.loadExchanges();
  },

  // 加载兑换记录
  async loadExchanges() {
    try {
      // 状态值映射：前端筛选值 -> 后端接口值
      const statusValueMap: { [key: string]: string } = {
        'all': '',
        'pending': '1',    // 待发货
        'shipped': '2',    // 已发货  
        'completed': '3'   // 已收货
      };
      
      const result = await getIntegralOrderList({
        status: statusValueMap[this.data.currentFilter] || ''
      });
      if (result.data) {
        // 转换数据格式以匹配模板
        const formattedExchanges: ExchangeRecord[] = result.data.map((item: any) => ({
          id: item.id,
          orderId: item.order_id,
          productName: item.store_name,
          productImage: item.image,
          points: item.total_price,
          exchangeTime: item.add_time,
          status: item.status,
          statusName: item.status_name,
          recipientName: item.real_name,
          recipientPhone: item.user_phone,
          recipientAddress: item.user_address,
          trackingNumber: item.delivery_id || '',
          deliveryName: item.delivery_name || '',
          deliveryType: item.delivery_type || '',
          totalNum: item.total_num,
          price: item.price,
          remark: item.remark || ''
        }));
        
        this.setData({ exchanges: formattedExchanges });
      }
    } catch (error) {
      console.error('加载兑换记录失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
    this.renderExchanges();
  },

  // 渲染兑换记录列表
  renderExchanges() {
    let filteredExchanges: ExchangeRecord[] = this.data.exchanges;
    
    if (this.data.currentFilter !== 'all') {
      // 根据状态筛选
      const statusMap: { [key: string]: number[] } = {
        'pending': [1],    // 待发货
        'shipped': [2],    // 已发货
        'completed': [3]   // 已收货
      };
      
      const targetStatuses = statusMap[this.data.currentFilter] || [];
      filteredExchanges = this.data.exchanges.filter(e => targetStatuses.includes(e.status));
    }
    
    this.setData({ filteredExchanges });
  },

  // 按状态筛选
  filterByStatus(e: any) {
    const status = e.currentTarget.dataset.status;
    this.setData({ currentFilter: status });
    this.loadExchanges();
  },

  // 查看兑换详情
  viewExchangeDetail(e: any) {
    const exchangeId = e.currentTarget.dataset.id;
    const exchange = this.data.exchanges.find(e => e.id === exchangeId);
    
    if (exchange) {
      const statusInfo = this.data.statusMap[exchange.status];
      let content = `商品：${exchange.productName}\n积分：${exchange.points}\n状态：${statusInfo.text}\n收件人：${exchange.recipientName}\n电话：${exchange.recipientPhone}\n地址：${exchange.recipientAddress}`;
      
      if (exchange.trackingNumber) {
        content += `\n快递单号：${exchange.trackingNumber}`;
      }
      if (exchange.deliveryName) {
        content += `\n快递公司：${exchange.deliveryName}`;
      }
      if (exchange.remark) {
        content += `\n备注：${exchange.remark}`;
      }
      
      wx.showModal({
        title: '兑换详情',
        content: content,
        showCancel: false
      });
    }
  },

  // 搜索兑换记录
  searchExchanges() {
    wx.showModal({
      title: '搜索兑换记录',
      editable: true,
      placeholderText: '请输入商品名称或收件人姓名',
      success: (res) => {
        if (res.confirm && res.content) {
          const keyword = res.content.trim();
          const filteredExchanges = this.data.exchanges.filter(e => 
            e.productName.includes(keyword) || 
            e.recipientName.includes(keyword)
          );
          
          if (filteredExchanges.length === 0) {
            wx.showToast({
              title: '未找到相关兑换记录',
              icon: 'none'
            });
          } else {
            this.setData({ filteredExchanges });
          }
        }
      }
    });
  },

  // 跳转到积分商城
  goToPrizes() {
    goToPage(PAGES.PRIZES);
  }
});
